<?php
session_start();

require "getPageView.php";
require "getIpAddress.php";
require "getCoorAddress.php";

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/4 0004
 * Time: 10:56
 */
class player extends main
{
    function __construct()
    {
        parent::__construct();
    }

    /**
     * @return mixed
     *
     * 获取参赛选手
     */
    public function getPlayers()
    {
        $data["code"] = 0;
        $where = $_POST["where"];
        $searArr[] = "status = 1 and isLock = 0";
        if (!empty($where)) {
            $searArr[] = "(playerName like '%$where%' or id = '$where')";
        }

        $pageSize = $_POST["pageSize"] ? $_POST["pageSize"] : 6;
        $page = $_POST["currentPage"] ? $_POST["currentPage"] : 1;
        $config = array("tableName" => "vote_player", "selectField" => "id,playerName,playerPic,currentNum,shareNum,playerTitle,headimgurl,openid", "orderBy" => "id asc", "pageSize" => $pageSize, "page" => $page, "searchCondition" => $searArr);
        $result = main::getList($config);
        $returnPage = getPageView::addPageView();
        $returnList = $this->getTotal();
        $returnTotal = array_merge_recursive($returnPage, $returnList);
        if (count($result["list"]) > 0) {
            $data['code'] = 1;
            $data['msg'] = '加载数据成功...';
            $data['result'] = $this->dealArray($result["list"]);
            $data['totalInfo'] = $returnTotal;
        } else {
            $data["msg"] = "没有数据可以显示...";
            $data['totalInfo'] = $returnTotal;
        }
        return $data;
    }

    /**
     * @return mixed
     *
     * 获取参赛选手
     */
    public function getPlayer()
    {
        $data["code"] = 0;
        $where = $_POST["where"];
        $searArr[] = "status = 1 and isLock = 0";
        if (!empty($where)) {
            $searArr[] = "(playerName like '%$where%' or id = '$where')";
        }

        $pageSize = $_POST["pageSize"] ? $_POST["pageSize"] : 6;
        $page = $_POST["currentPage"] ? $_POST["currentPage"] : 1;
        $config = array("tableName" => "vote_player", "selectField" => "id,playerName,playerPic,currentNum,shareNum,playerTitle,headimgurl,openid", "orderBy" => "id asc", "pageSize" => $pageSize, "page" => $page, "searchCondition" => $searArr);
        $result = main::getList($config);
        if (count($result["list"]) > 0) {
            $data['code'] = 1;
            $data['msg'] = '加载数据成功...';
            $data['result'] = $this->dealArray($result["list"]);
        } else {
            $data["msg"] = "没有数据可以显示...";
        }
        return $data;
    }

    /**
     * @return mixed
     *
     * 通过参数获取参赛选手信息
     */
    public function getPlayerByPara()
    {
        $data["code"] = 0;
        $paraId = $_POST["paraId"];
        $openId = $_POST["openId"];
        $searArr[] = "status = 1 and isLock = 0";
        if (!empty($paraId)) {
            $searArr[] = "id = $paraId";
        }
        if (!empty($openId)) {
            $searArr[] = "openid = '$openId'";
        }
        $config = array("tableName" => "vote_player", "selectField" => "id,playerName,playerPic,currentNum,shareNum,playerTitle,headimgurl,openid", "orderBy" => "id asc", "pageSize" => NULL, "page" => NULL, "searchCondition" => $searArr);
        $result = main::getList($config);

        if (count($result["list"]) > 0) {
            $data['code'] = 1;
            $data['msg'] = '加载数据成功...';
            $data['result'] = $this->dealArray($result["list"]);
        } else {
            $data["msg"] = "没有数据可以显示...";
        }
        return $data;
    }

    /**
     * @param $list
     * @return mixed
     *
     * 处理图片
     */
    private function dealArray($list)
    {
        foreach ($list as $key => $val) {
            $list[$key]["playerPic"] = explode(",", $val["playerPic"]);
        }
        return $list;
    }

    /**
     * @return mixed
     *
     * 投票
     */
    public function vote()
    {
        $data["code"] = 0;
        $params = $_POST["params"];

        $sql = "select voteStartTime as column1,voteEndTime as column2,voteNumPer as column3,isForMyself as column4 from vote_voteset union select isCheckCode,isLimitArea,limitArea,(select voteStatus from vote_baseset) from vote_safeset";
        $returnArr = main::getArrayBySql($sql);

        if ($returnArr[1]["column4"] == 1) {
            $startTime = $returnArr[0]["column1"];
            $endTime = $returnArr[0]["column2"];
            $nowTime = date("Y-m-d H:i:s", time());
            if (strtotime($startTime) > strtotime($nowTime)) {
                $data["msg"] = "投票时间还未开始,敬请期待...";
                return $data;
            } else if (strtotime($nowTime) > strtotime($endTime)) {
                $data["msg"] = "你来晚了,投票时间已截止...";
                return $data;
            } else {
                $openId = $params["openId"];
                $voteOpenId = $params["voteOpenId"];
                $isForMySelf = $returnArr[0]["column4"];
                if ($openId == $voteOpenId && $isForMySelf == 0) {
                    $data["msg"] = "活动规则不能自己为自己投票...";
                    return $data;
                } else {
                    $isLimitArea = $returnArr[1]["column2"];
                    $getArr = getCoorAddress::getAddress($params["longitude"], $params["latitude"]);
                    $ip = getCoorAddress::getClientIp();
                    $params["voteIp"] = $ip;
                    if ($isLimitArea == 1) {
                        $province = $getArr["province"];
                        $city = $getArr["city"];
                        $str = $returnArr[1]["column3"];
                        if (strstr($str, $city)) {
                            $data = $this->addRecord($params, $voteOpenId, $returnArr);
                        } else {
                            if (strstr($str, $province)) {
                                $data = $this->addRecord($params, $voteOpenId, $returnArr);
                            } else {
                                $data = $this->addRecord($params, $voteOpenId, $returnArr);
                            }
                        }
                    } else {
                        $data = $this->addRecord($params, $voteOpenId, $returnArr);
                    }
                }
            }
        } else {
            $data["msg"] = "投票通道已关闭,我们相约下次活动...";
            return $data;
        }
        return $data;
    }

    /**
     * @return mixed
     *
     * 获取报名页图片
     */
    public function getPubPic()
    {
        $sql = "select pubPic from vote_contentset";
        $sqlList = main::getArrayBySql($sql);
        return $sqlList[0];
    }

    /**
     * @param $list
     * @return mixed
     *
     * 添加投票记录
     */
    private function addRecord($list, $voteOpenId, $returnArr)
    {
        $data["code"] = 0;
        $nowDate = date("Y-m-d", time());
        $sqlCount = "select count(id) as voteNum from vote_record where voteOpenId = '$voteOpenId' and DATE_FORMAT(voteTime,'%Y-%m-%d') = '$nowDate'";
        $sqlCountList = main::getArrayBySql($sqlCount);
        $voteNum = $sqlCountList[0]["voteNum"];
        $voteNumPer = $returnArr[0]["column3"];
        if ($voteNumPer == $voteNum || $voteNumPer < $voteNum) {
            $data["msg"] = "每天限定同一微信投票次数$voteNumPer 次,请明天再来...";
        } else {
            $sqlVote = "select id from vote_voter where openId = '$voteOpenId'";
            $sqlVoteList = main::getArrayBySql($sqlVote);
            if (count($sqlVoteList) > 0) {
                $data["msg"] = "您已经列入限制投票的名单,如有疑问,请联系管理员...";
            } else {
                unset($list["openId"]);
                unset($list["latitude"]);
                unset($list["longitude"]);
                $list["voteTime"] = date("Y-m-d H:i:s", time());
                $insertTitle = "insert into vote_record (";
                $insertValue = "(";
                foreach ($list as $key => $val) {
                    $insertTitle .= $key . ',';
                    $insertValue .= "'$val',";
                }
                $insertTitle = substr($insertTitle, 0, strlen($insertTitle) - 1) . ")";
                $insertValue = substr($insertValue, 0, strlen($insertValue) - 1) . ")";
                $sqlArr[] = $insertTitle . " values " . $insertValue;
                $voteUserId = $list["voteUserId"];
                $sqlArr[] = "update vote_player set currentNum = currentNum + 1 where id = $voteUserId";

                global $myPDO;
                $result = $myPDO->queryTransAction($sqlArr);
                if ($result) {
                    $data["code"] = 1;
                    $data["msg"] = "投票成功,谢谢您的参与...";
                } else {
                    $data["msg"] = "投票失败,如有疑问请联系管理员...";
                }
            }
        }
        return $data;
    }

    /**
     * @return mixed
     *
     * 添加分享
     */
    public function addShare()
    {
        $data["code"] = 0;
        $playerId = $_POST["playerId"];
        $saveArr["id"] = $playerId;
        $saveArr["tableName"] = "vote_player";
        $saveArr["list"]["shareNum"] = "shareNum + 1";
        $result = main::save($saveArr);

        if ($result) {
            $data["code"] = 1;
            $data["msg"] = "分享成功...";
        } else {
            $data["msg"] = "分享失败...";
        }

        return $data;
    }

    /**
     * @return mixed
     *
     * 添加参赛选手
     */
    public function addPlayer()
    {
        $data["code"] = 0;
        $params = $_POST["params"];
        $mobile = $params["playerMobile"];
        $openId = $params["openId"];
        $sql = "select id from vote_player where playerMobile = '$mobile' or openid = '$openId'";
        $sqlList = main::getArrayBySql($sql);
        if (count($sqlList) > 0) {
            $data["msg"] = "该手机号码已参与报名,请重新输入...";
        } else {
            $sql = "select signStartTime,signEndTime from vote_voteset";
            $list = main::getArrayBySql($sql);
            $returnArr = $list[0];
            $startTime = $returnArr["signStartTime"];
            $endTime = $returnArr["signEndTime"];
            $nowTime = date("Y-m-d H:i:s", time());
            if (strtotime($startTime) > strtotime($nowTime)) {
                $data["msg"] = "报名时间还未开始,敬请期待...";
            } else if (strtotime($nowTime) > strtotime($endTime)) {
                $data["msg"] = "你来晚了,报名时间已截止...";
            } else {
                $playerInfo["openid"] = $openId;
                $playerInfo["nickname"] = $params["nickname"];
                $playerInfo["headimgurl"] = $params["headimgurl"];
                $playerInfo["playerName"] = $params["playerName"];
                $playerInfo["playerMobile"] = $params["playerMobile"];
                $playerInfo["playerTitle"] = $params["playerTitle"];
                $playerInfo["playerPic"] = $params["playerPic"];
                $playerInfo["createTime"] = date("Y-m-d m:i:s", time());
                $baseSet = constant::getBaseSet();
                $playerInfo["status"] = $baseSet["checkStatus"];
                $saveArr["tableName"] = "vote_player";
                $saveArr["list"] = $playerInfo;

                $result = main::save($saveArr);

                if ($result) {
                    $data["code"] = 1;
                    $data["msg"] = "报名成功,快去投票吧...";
                } else {
                    $data["msg"] = "报名失败,请检查资料正确性...";
                }
            }
        }
        return $data;
    }

    /**
     * @param $imgList
     * @return bool|string
     *
     * 获取图片
     */
    public function getResApi($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return ($result);
    }

    /**
     * @return mixed
     *
     * 获取统计信息
     */
    private function getTotal()
    {
        $sql = "select (select count(id) from vote_record) as voteNum,(select count(id) from vote_player where STATUS = 1 and isLock = 0) as playerNum,(select voteTitle from vote_baseset) as voteTitle,(select topPic from vote_contentset) as pic,(select pubPic from vote_contentset) as pubPic,(select voteRule from vote_contentset) as voteRule,(select backMusic from vote_baseset) as backMusic,(select voteEndTime from vote_voteset) as voteEndTime";
        $sqlList = main::getArrayBySql($sql);
        return $sqlList[0];
    }

    /**
     * @return mixed
     *
     * 获取分享的设置信息
     */
    public function getShareSet()
    {
        $sql = "select shareTitle,shareIcon,shareDesc from vote_shareset";
        $sqlList = main::getArrayBySql($sql);
        return $sqlList[0];
    }

}